﻿using System;
using System.Dynamic;
using System.Text.Encodings.Web;
using System.Text.Json;
using zijian666.Core.Abstractions;
using zijian666.SuperConvert.Core;
using zijian666.SuperConvert.Extensions;

namespace zijian666.SuperConvert.Json
{
    public class JsonStringSerializer : IStringSerializer
    {
        private readonly JsonSerializerOptions _deserializeOptions = new JsonSerializerOptions() {
            Converters = { new JsonElementTranslator(), new JsonValueConverter<DateTime>(), new JsonValueConverter<TimeSpan>(), new JsonValueConverter<DateTimeOffset>(), new JsonValueConverter<Guid>() }
        };

        private readonly JsonSerializerOptions _serializeOptions = new JsonSerializerOptions() {
            Converters = { new JsonValueConverter<DateTime>(), new JsonValueConverter<TimeSpan>(), new JsonValueConverter<DateTimeOffset>(), new JsonValueConverter<Guid>(), new PackagingObjectJsonConverert() },
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
        };

        public string ToString(object value)
        {
            using var _ = ConvertContext.Scope();
            return JsonSerializer.Serialize(value, _serializeOptions);
        }

        public object ToObject(string value, Type type = null)
        {
            using var context = ConvertContext.Scope();
            return JsonSerializer.Deserialize(value, type ?? typeof(object), _deserializeOptions);
        }

        public string Protocol => "json";
    }
}
